﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BCZadmin.Helper
{
    /// <summary>
    /// 播放声音的类
    /// </summary>
    public class Music
    {
        [DllImport("winmm.dll")]
        static extern long mciSendString(string strCommand,
            string strReturn, int iReturnLength, int hwndCallback);
        public string Path { get; set; }

        public Music(string path)
        {
            this.Path = path;
        }
        /// <summary>
        /// 播放声音的方法
        /// </summary>
        public void PlayMusic()
        {
            mciSendString(@"close temp", " ", 0, 0);//停止上一次的声音播放
            mciSendString(@"open " + Path + " alias temp", null, 0, 0);//打开文件作为当前的声音文件并命名
            mciSendString(@"play temp", " ", 0, 0);//播放命名的声音
        }
        /// <summary>
        /// 重复播放声音的方法
        /// </summary>
        public void PlayMusicRpeat()
        {
            mciSendString(@"close temp", " ", 0, 0);//停止上一次的声音播放
            mciSendString(@"open " + Path + " alias temp", null, 0, 0);//打开文件作为当前的声音文件并命名
            mciSendString(@"play temp repeat", " ", 0, 0);//播放命名的声音
        }
        /// <summary>
        /// 用于播放可能同时发生的声音
        /// </summary>
        //public void MusicStart()
        //{
        //    Thread P = new Thread(PlayMusic);
        //    P.IsBackground = true;
        //    P.Start();
        //}
        /// <summary>
        /// 用异步创建一个线程
        /// 利用lambda
        /// </summary> 
        public void MusicStart()
        {
            ThreadStart r = new ThreadStart(() =>
            {
                PlayMusic();
            });
            r.BeginInvoke(null, null);
        }
    }
}
